/****************************************************************************
 * Copyright 2009 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.filter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Formatter;

/**
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class FilteringException extends RuntimeException {
    private static final long serialVersionUID = -2945658756136792383L;
    private final Collection<Throwable> errors;

    /**
     *
     * @param errors
     *      collection of errors to be printed
     *      once the {@link FilterImpl#throwFailedFilteringExceptions()} is called.
     */
    public FilteringException(Collection<Throwable> errors){
        this.errors = errors;
        //noinspection ThrowableResultOfMethodCallIgnored
        initCause(onlyCauseFor(this.errors));
    }

    /**
     *
     * @param heading
     *      an error message heading.
     * @param errorMessages
     *      a set of recorded errors.
     * @return
     *      the formatted message for an exception with the specified messages.
     */
    public static String makeCuteMessage(String heading, Collection<Throwable> errorMessages) {
        final Formatter formatter = new Formatter().format(heading).format(":%n%n");
        int index = 1;

        for (Throwable each : errorMessages) {
            formatter.format("%s) %s%n", index++, each.getMessage());
            final Throwable cause = each.getCause();
            //noinspection ThrowableResultOfMethodCallIgnored
            if (onlyCauseFor(errorMessages) == null && cause != null) {
                final StringWriter writer = new StringWriter();
                cause.printStackTrace(new PrintWriter(writer));
                formatter.format("Caused by: %s", writer.getBuffer());
            }
            formatter.format("%n");
        }

        if (errorMessages.size() == 1) {
            formatter.format("1 error");
        } else {
            formatter.format("%s errors", errorMessages.size());
        }

        return formatter.toString();
 }

    @Override
    public String getMessage() {
        return makeCuteMessage("FilterQ filtering errors", errors);
    }

  /**
   * @param errors
   *      collection of errors to be printed
   *      once the {@link FilterImpl#throwFailedFilteringExceptions()} is called.
   * @return the cause throwable if there is exactly one cause in
   *        {@code errors}. If there are zero or multiple errors
   *        with causes, null is returned.
   */
   public static Throwable onlyCauseFor(Collection<Throwable> errors) {
        Throwable onlyCause = null;
        for (Throwable message : errors) {
            final Throwable messageCause = message.getCause();

            if (messageCause == null) {
                continue;
            }

            if (onlyCause != null) {
                return null;
            }

            onlyCause = messageCause;
        }

          return onlyCause;
   }
}
